home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 5 / Apprentice-Release5.iso / Source Code / By the Book / Learn C++ (CodeWarrior) / Chap 07.05 - subscript / subscript.cp < prev    next >
Text File  |  1995-10-20  |  826b  |  56 lines

  1. #include <iostream.h>
  2. #include <string.h>
  3.  
  4. const short kMaxNameLength = 40;
  5.  
  6. //---------------------------------------  Name
  7.  
  8. class Name
  9. {
  10.     private:
  11.         char        nameString[ kMaxNameLength ];
  12.         short        nameLength;
  13.         
  14.     public:
  15.                     Name( char *name );
  16.         void    operator()();
  17.         char    &operator[]( short index );
  18. };
  19.  
  20. Name::Name( char *name )
  21. {
  22.     strcpy( nameString, name );
  23.     nameLength = strlen( name );
  24. }
  25.  
  26. void    Name::operator()()
  27. {
  28.     cout << nameString << "\n";
  29. }
  30.  
  31. char& Name::operator[]( short index )
  32. {
  33.     if ( ( index < 0 ) || ( index >= nameLength ) )
  34.     {
  35.         cout << "index out of bounds!!!\n";
  36.         return( nameString[ 0 ] );
  37.     }
  38.     else
  39.         return( nameString[ index ] );
  40. }
  41.  
  42.  
  43. //---------------------------------------  main()
  44.  
  45. int    main()
  46. {
  47.     Name        pres( "B. J. Clinton" );
  48.     
  49.     pres[ 3 ] = 'X';
  50.     pres();
  51.     
  52.     pres[ 25 ] = 'Z';
  53.     pres();
  54.     
  55.     return 0;
  56. }